package fr.mywiki.view.web.servlet;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.mywiki.business.file.FileLite;
import fr.mywiki.business.file.FileManager;
import fr.mywiki.model.ejbAdapter.DataController;
import fr.mywiki.model.ejbAdapter.Value;

/**
 * This servlet enables the display of a image whose identifier or name is given
 * as a request parameter.
 * 
 * FIXME Quand on est sur la page d'une entry, cliquer sur une image n'ouvre pas 
 * de popup, l'image s'affiche dans la page en cours
 * 
 * @web.servlet name="DisplayImage" display-name="DisplayImage"
 * @web.servlet-mapping url-pattern="/DisplayImage.do"
 */
public class DisplayImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/** Url Pattern of this servlet, can be used to build hyperlinks */
	public static final String URL_PATTERN = "DisplayImage.do";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		doPost(request, response);
	}

	/**
	 * Finds the <code>FileLite</code> object with the request-specified
	 * identifier or name.
	 * 
	 * TODO test it
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		FileLite file = null;

		String fileName = request.getParameter(FileLite.FIELD_NAME);

		Long fileId = null;
		if (fileName == null) {
			fileId = new Long(request.getParameter(Value.FIELD_ID));
			file = (FileLite) DataController.getValue(fileId, FileLite.TYPE_ENT);
		} else {
			file = FileManager.findFileByName(fileName);
		}

		response.setContentType("image/" + FileManager.getFileExtension(file));
		response.setHeader("Content-Disposition:", "attachment; filename=\""
				+ file.getName() + "\";");

		ServletOutputStream stream = response.getOutputStream();
		byte[] content = file.getContent();
		response.setContentLength(content.length);
		stream.write(content, 0, content.length);
		stream.close();
	}
}